package com.leyou.item.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.leyou.common.constants.MQConstants;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exception.LyException;
import com.leyou.common.utils.BeanHelper;
import com.leyou.common.vo.PageResult;
import com.leyou.item.dto.*;
import com.leyou.item.entity.Sku;
import com.leyou.item.entity.Spu;
import com.leyou.item.entity.SpuDetail;
import com.leyou.item.mapper.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.leyou.common.constants.MQConstants.Exchange.ITEM_EXCHANGE_NAME;
import static com.leyou.common.constants.MQConstants.RoutingKey.ITEM_DOWN_KEY;
import static com.leyou.common.constants.MQConstants.RoutingKey.ITEM_UP_KEY;

@Service
public class GoodsService {

    @Autowired
    private SpuMapper spuMapper;
    @Autowired
    private SpuDetailMapper spuDetailMapper;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private BrandService brandService;
    @Autowired
    private SkuMapper skuMapper;

    @Autowired
    private AmqpTemplate amqpTemplate;


    public PageResult<SpuDTO> querySpuByPage(String key, Integer page, Integer rows, Boolean saleable) {
        // 分页设置
        PageHelper.startPage(page, rows);
        // 条件过滤
        Example example = new Example(Spu.class);
        Example.Criteria criteria = example.createCriteria();
        // 判断关键字
        if(StringUtils.isNotBlank(key)){
            criteria.andLike("name", "%"+key+"%");
        }
        // 是否上下架
        if(saleable!=null){
            criteria.andEqualTo("saleable", saleable);
        }
        // 加一个排序: 加入一个排序，最后修改的商品最先展示
        example.setOrderByClause("update_time DESC");

        // 查询
        List<Spu> spuList = spuMapper.selectByExample(example);
        // 判空
        if(CollectionUtils.isEmpty(spuList)){
            throw new LyException(ExceptionEnum.GOODS_NOT_FOUND);
        }
        // 总记录数
        PageInfo<Spu> spuPageInfo = new PageInfo<>(spuList);
        long total = spuPageInfo.getTotal();
        // 当前页数据
        List<Spu> list = spuPageInfo.getList();
        List<SpuDTO> spuDTOList = BeanHelper.copyWithCollection(list, SpuDTO.class);

        //处理分类名称和品牌名称
        handleCategoryAndBrandName(spuDTOList);

        // 封装成DTO对象
        return new PageResult<>(spuDTOList, total);
    }

    // 处理分类和品牌的名称
    private void handleCategoryAndBrandName(List<SpuDTO> spuDTOList) {
        for (SpuDTO spuDTO : spuDTOList) {
            // 品牌名称
            Long brandId = spuDTO.getBrandId();
            BrandDTO brandDTO = brandService.queryBrandById(brandId);
            spuDTO.setBrandName(brandDTO.getName());
            // 分类名称
            List<Long> categoryIds = spuDTO.getCategoryIds();
            // 批量查询分类
            List<CategoryDTO> categoryDTOList = categoryService.queryCategoryByIds(categoryIds);
            // 方式二： 流
            String categoryName = categoryDTOList.stream().map(CategoryDTO::getName).collect(Collectors.joining("/"));
            spuDTO.setCategoryName(categoryName);
            // 方式一
            /*StringBuilder sb = new StringBuilder();
            for (CategoryDTO cd : categoryDTOList) {
                sb.append(cd.getName()).append("/");
            }
            //还要处理最后一个斜杆
            sb.toString().substring(0, sb.toString().length() - 1);*/
        }
    }

    /**
     * 保存商品
     * @param spuDTO
     */
    @Transactional // 事务控制
    public void saveGoods(SpuDTO spuDTO) {
        // 把dto转成po
        Spu spu = BeanHelper.copyProperties(spuDTO, Spu.class);
        // 保存spu
        int count = spuMapper.insertSelective(spu);
        if(count != 1){
            throw new LyException(ExceptionEnum.INSERT_OPERATION_FAIL);
        }
        // 获取spu的id
        Long spuId = spu.getId();

        // 保存spuDetail
        SpuDetailDTO spuDetailDTO = spuDTO.getSpuDetail();
        // 把dto转成po
        SpuDetail spuDetail = BeanHelper.copyProperties(spuDetailDTO, SpuDetail.class);
        spuDetail.setSpuId(spuId); // 设置主键
        count = spuDetailMapper.insertSelective(spuDetail);
        if(count != 1){
            throw new LyException(ExceptionEnum.INSERT_OPERATION_FAIL);
        }

        // 保存sku的集合
        List<SkuDTO> skuDTOList = spuDTO.getSkus();
        // 把dto转成po
        List<Sku> skuList = BeanHelper.copyWithCollection(skuDTOList, Sku.class);
        // 设置Spu的id
        skuList.forEach(s -> {
            s.setSpuId(spuId);
        });
        // 批量插入
        count = skuMapper.insertList(skuList);
        if(count != skuList.size()){
            throw new LyException(ExceptionEnum.INSERT_OPERATION_FAIL);
        }
    }

    /**
     * 上下架操作
     * @param spuId
     * @param saleable
     */
    @Transactional // 加入事务操作
    public void updateSaleable(Long spuId, Boolean saleable) {
        // 1、更新spu
        Spu record = new Spu();
        record.setId(spuId);
        record.setSaleable(saleable);
        int count = spuMapper.updateByPrimaryKeySelective(record);
        if(count != 1){
            throw new LyException(ExceptionEnum.UPDATE_OPERATION_FAIL);
        }

        // 2、更新sku： update tb_sku set enable = ? where spu_id = ?
        // 2.1 准备更新的内容
        Sku sku = new Sku();
        sku.setEnable(saleable);
        // 2.2 更新的条件
        Example example = new Example(Sku.class);
        example.createCriteria().andEqualTo("spuId", spuId);
        count = skuMapper.updateByExampleSelective(sku, example);
        if(count < 1){
            throw new LyException(ExceptionEnum.UPDATE_OPERATION_FAIL);
        }

        // 3、上下架的操作，我们需要发送消息到队列中： 静态化服务和搜索微服务消费
        amqpTemplate.convertAndSend(ITEM_EXCHANGE_NAME, (saleable ? ITEM_UP_KEY : ITEM_DOWN_KEY) , spuId);
    }

    /**
     * 查询spu详情数据
     * @param spuId
     * @return
     */
    public SpuDetailDTO querySpuDetailBySpuId(Long spuId) {
        SpuDetail spuDetail = spuDetailMapper.selectByPrimaryKey(spuId);
        if(spuDetail == null){
            throw new LyException(ExceptionEnum.GOODS_NOT_FOUND);
        }
        return BeanHelper.copyProperties(spuDetail, SpuDetailDTO.class);
    }

    /**
     * 查询sku集合
     * @param spuId
     * @return
     */
    public List<SkuDTO> querySkuListBySpuId(Long spuId) {
        Sku record = new Sku();
        record.setSpuId(spuId);
        List<Sku> skuList = skuMapper.select(record);
        if(CollectionUtils.isEmpty(skuList)){
            throw new LyException(ExceptionEnum.GOODS_NOT_FOUND);
        }
        return BeanHelper.copyWithCollection(skuList, SkuDTO.class);
    }

    /**
     * 更新商品
     * @param spuDTO
     */
    @Transactional
    public void updateGoods(SpuDTO spuDTO) {
        // 1、 删除sku
        Long spuId = spuDTO.getId();
        if(spuId == null){
            throw new LyException(ExceptionEnum.INVALID_PARAM_ERROR);
        }
        Sku record = new Sku();
        record.setSpuId(spuId);
        // 查询条数
        int count = skuMapper.selectCount(record);
        if(count > 0){
            // 删除
            int delete = skuMapper.delete(record);
            if(count != delete){
                throw new LyException(ExceptionEnum.UPDATE_OPERATION_FAIL);
            }
        }

        // 2、 更新SPU
        Spu spu = BeanHelper.copyProperties(spuDTO, Spu.class);
        spu.setSaleable(null); // 更新的时候我们不想让用户在修改页面做上下架操作
        spu.setUpdateTime(null);
        spu.setCreateTime(null);
        count = spuMapper.updateByPrimaryKeySelective(spu);// 更新非空数据
        if(count != 1){
            throw new LyException(ExceptionEnum.UPDATE_OPERATION_FAIL);
        }

        // 3、 更新SpuDetail
        SpuDetail spuDetail = BeanHelper.copyProperties(spuDTO.getSpuDetail(), SpuDetail.class);
        spuDetail.setSpuId(spuId);
        count = spuDetailMapper.updateByPrimaryKeySelective(spuDetail);
        if(count != 1){
            throw new LyException(ExceptionEnum.UPDATE_OPERATION_FAIL);
        }

        // 4、批量插入Sku集合
        List<SkuDTO> skuDTOList = spuDTO.getSkus();
        // 把dto转成po
        List<Sku> skuList = BeanHelper.copyWithCollection(skuDTOList, Sku.class);
        // 设置Spu的id
        skuList.forEach(s -> {
            s.setSpuId(spuId);
        });
        // 批量插入
        count = skuMapper.insertList(skuList);
        if(count != skuList.size()){
            throw new LyException(ExceptionEnum.UPDATE_OPERATION_FAIL);
        }
    }

    public SpuDTO querySpuById(Long id) {
        Spu spu = spuMapper.selectByPrimaryKey(id);
        if(spu == null){
            throw  new LyException(ExceptionEnum.INVALID_PARAM_ERROR);
        }
        return BeanHelper.copyProperties(spu, SpuDTO.class);
    }

    /**
     * 查询sku
     * @param ids
     * @return
     */
    public List<SkuDTO> querySkuListByIds(List<Long> ids) {
        List<Sku> skuList = skuMapper.selectByIdList(ids);
        if(CollectionUtils.isEmpty(skuList)){
            throw new LyException(ExceptionEnum.GOODS_NOT_FOUND);
        }
        return BeanHelper.copyWithCollection(skuList, SkuDTO.class);
    }

    /**
     * 扣除商品库存
     * @param cartsMap
     */
    @Transactional
    public void minusStock(Map<Long, Integer> cartsMap) {
        for (Map.Entry<Long, Integer> entry : cartsMap.entrySet()) {
            Long skuId = entry.getKey(); // sku的id
            Integer num = entry.getValue(); // 扣除的量
            /**
             * 商品超卖： 减成负数，库存量变为了负数
             *      1、先查询，然后比对库存量，如果足够才能减库存【性能不好】
             *      2、使用分布式锁，变成串行【性能不好】
             *      3、无符号： 不允许出现负数【数据库自己维护，性能好，终极解决方案】
             */
            int count = skuMapper.minusStock(skuId, num);
            if(count != 1){
                throw new LyException(ExceptionEnum.STOCK_NOT_ENOUGH_ERROR);
            }
        }
    }
}
